<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>WebSocket</title>
</head>

<body>
  <script>
    // 只需要new一下就可以创建一个websocket的实例
    // 我们要去连接ws协议
    // 这里对应的端口就是服务端设置的端口号9999
    let ws = new WebSocket('ws://localhost:9999');

    const getReadyState = () => {
      let readyState = ws.readyState;

      switch (readyState) {
        case 0:
          console.log("readyState:正在链接中");
          break;
        case 1:
          console.log("readyState:已经链接并且可以通讯");
          break;
        case 2:
          console.log("readyState:连接正在关闭");
          break;
        case 3:
          console.log("readyState:连接已关闭或者没有链接成功");
          break;
        default:
          break;
      }
    }
    getReadyState();

    // onopen是客户端与服务端建立连接后触发
    ws.onopen = () => {
      ws.send("你好，服务端");
      getReadyState();
    }

    // onmessage是当服务端给客户端发来消息的时候触发
    ws.onmessage = function (res) {
      console.log(res);   // 打印的是MessageEvent对象
      // 真正的消息数据是 res.data
      document.write(`来自服务端的消息：${res.data}`);
      getReadyState();
    };

    // 断开 websocket 连接成功触发事件
    ws.onclose = function () {
      console.log("连接已关闭");
      getReadyState();
    };
  </script>
</body>

</html>